<template>
    <l-page customClass="h-full flex flex-col" ref="page">
        <l-navbar title="选择城市"></l-navbar>
        <view class="m-3">当前定位：</view>
        <view class="flex mx-3 mb-3">
            <u-tag :text="setting.currentRegion"></u-tag>
        </view>
        <view id="list"></view>
        <u-index-list :index-list="indexList" ref="listBox">
            <template v-for="(item, index) in itemArr" :key="index">
                <u-index-item>
                    <!-- #ifndef APP-NVUE -->
                    <u-index-anchor :text="indexList[index]"></u-index-anchor>
                    <!-- #endif -->
                    <view class="ml-3 border-b border-gray-300 py-3"
                        :class="{ 'border-none': index == item.length - 1 }" v-for="(cell, index) in item" :key="cell"
                        @tap="change(cell)">
                        {{ cell }}
                    </view>
                </u-index-item>
            </template>
        </u-index-list>
    </l-page>
</template>
<script setup lang="ts">
import Setting from '@/stores/settings'
import { pinyin } from 'pinyin-pro';
import { onMounted } from 'vue';
import { ref } from 'vue';
let indexList = ref<string[]>([]), itemArr = ref<Array<Array<string>>>([]);
const setting = Setting()
setting.getRegions().then(res => {
    const list = res.map(item => item.children);
    const obj: { [key: string]: Array<string> } = {}
    list.flat().forEach(item => {
        const first = pinyin(item.label, { type: 'array', toneType: 'none', pattern: 'first' })[0]?.toUpperCase()
        if (!obj[first]) obj[first] = []
        obj[first].push(item.label)
    });
    indexList.value = Object.keys(obj).sort()
    itemArr.value = []
    indexList.value.forEach(item => {
        itemArr.value.push(obj[item])
    })
})

const change = (cell: string) => {
    setting.currentRegion = cell;
    uni.navigateBack()
}
let listBox = ref<any>(null)
onMounted(() => {
    // 解决该死的bug 替换组件内的方法
    uni.createSelectorQuery().select('#list').boundingClientRect((res: any) => {
        listBox.value.setValueForTouch = function (currentIndex: number) {
            if (currentIndex === this.activeIndex)
                return;
            this.activeIndex = currentIndex;
            this.scrollTop = this.children[currentIndex].top - res.top;
        }
    }).exec()

})
</script>